<?php

namespace backend\models;

use Yii;
use backend\helpers\FileNameInflector;

/**
 * This is the model class for table "project_donation".
 *
 * @property int $id
 * @property int $donor_id
 * @property float $price
 * @property int $is_direct_donation
 * @property int|null $registry_number
 * @property string|null $own_number
 * @property string|null $date_sign
 * @property string|null $date_realize
 * @property string|null $subject
 * @property string|null $filename
 * @property int $project_id
 *
 * @property Donor $donor
 * @property Project $project
 */
class ProjectDonation extends \yii\db\ActiveRecord
{
    const BUCKET_NAME = 'ogikm-donor-contracts';

    const CONTRACT = 0;
    const DIRECT = 1;

    const PROXY = 1;
    const OWN = 0;

    public $contractFile;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'project_donation';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['donor_id', 'price', 'project_id'], 'required'],
            [['donor_id', 'is_direct_donation', 'registry_number', 'project_id', 'is_proxy'], 'integer'],
            ['registry_number', 'unique'],
            [['price'], 'number'],
            [['date_sign', 'date_realize'], 'safe'],
            [['own_number', 'filename'], 'string', 'max' => 255],
            [['subject'], 'string', 'max' => 512],
            [['donor_id'], 'exist', 'skipOnError' => true, 'targetClass' => Donor::className(), 'targetAttribute' => ['donor_id' => 'id']],
            [['project_id'], 'exist', 'skipOnError' => true, 'targetClass' => Project::className(), 'targetAttribute' => ['project_id' => 'id']],
            [['contractFile', ], 'file', 'extensions' => 'doc, docx, pdf, zip', 'maxSize' => 1024*1024*12],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'donor_id' => 'Донор',
            'price' => 'Сумма пожертвования',
            'is_direct_donation' => 'Тип пожертвования',
            'registry_number' => 'Реестровый номер договора',
            'own_number' => 'Номер договора',
            'date_sign' => 'Дата подписания договора',
            'date_realize' => 'Дата предоставления отчёта (до...)',
            'subject' => 'Предмет договора',
            'filename' => 'Договор пожертвования',
            'project_id' => 'Проект',
            'contractFile' => 'Договор пожертвования',
            'is_proxy' => 'Прокси-пожертвование',
        ];
    }

    /**
     * Gets query for [[Donor]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getDonor()
    {
        return $this->hasOne(Donor::className(), ['id' => 'donor_id']);
    }

    /**
     * Gets query for [[Project]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getProject()
    {
        return $this->hasOne(Project::className(), ['id' => 'project_id']);
    }

    public static function generateRegistryNumber()
    {
        return random_int(10000000, 99999999);
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        // Запись новая
        if($insert)
        {
            // Спокойно сохраняем все файлы
            $this->insertContract();
        }
        // Запись обновляется
        else
        {
            // Необходимы дополнительные проверки
            $this->updateContract();
        }
        
        return true;
    }

    public function beforeDelete()
    {
        if (!parent::beforeDelete()) {
            return false;
        }

        $this->deleteContract();

        return true;
    }


    public function insertContract()
    {
        if($this->contractFile)
        {
            $s3 = Yii::$app->get('s3');

            $generatedName = 'Договор пожертвования №' 
                . FileNameInflector::specialSlug($this->own_number) . ' '
                . ' (' . $this->registry_number . ')'
                . '.' . $this->contractFile->extension;
    
            $result = $s3->commands()->upload($generatedName, $this->contractFile->tempName)->inBucket(self::BUCKET_NAME)->withAcl('private')->execute();
            
            $this->filename = $generatedName;
        }
    }

    public function updateContract()
    {
        if($this->contractFile)
        {
            if($this->filename)
            {
                $this->deleteContract();
            }
            $this->insertContract();
        }
    }

    public function deleteContract()
    {
        if($this->filename)
        {
            $s3 = Yii::$app->get('s3');
            $s3->commands()->delete($this->filename)->inBucket(self::BUCKET_NAME)->execute();
        }
    }
}
